package com.autoagent.ai_live_master.webSocket.handler;

import com.autoagent.ai_live_master.common.utils.MessageListener;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class SocketMessageListener implements MessageListener {

    private final SocketIOHandler socketIOHandler;

    private static final String DEFAULT_ROOM_ID = "000000"; // 或通过构造注入动态 roomId

    @Override
    public void onMessage(String content) {
        try {
            log.debug("SocketIOMessageListener onMessage: {}", content);
            socketIOHandler.broadcast(DEFAULT_ROOM_ID, content);
        } catch (Exception e) {
            log.error("Failed to broadcast message to SocketIO", e);
        }
    }

    @Override
    public void onComplete() {
        try {
            log.debug("SocketIOMessageListener onComplete");
            socketIOHandler.broadcast(DEFAULT_ROOM_ID, "{\"type\":\"complete\"}");
        } catch (Exception e) {
            log.error("Failed to broadcast completion message to SocketIO", e);
        }
    }

    @Override
    public void onError(Exception e) {
        log.error("SocketIOMessageListener encountered error", e);
        socketIOHandler.broadcast(DEFAULT_ROOM_ID,
                "{\"type\":\"error\",\"message\":\"" + e.getMessage() + "\"}");
    }
}

